home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c++ / 725 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  2.2 KB

  1. From: fjh@mundook.cs.mu.OZ.AU (Fergus Henderson)
  2. Message-ID: <4iaisq$2ai@mulga.cs.mu.OZ.AU>
  3. X-Original-Date: 15 Mar 1996 01:58:50 GMT
  4. Path: in2.uu.net!bounce-back
  5. Date: 15 Mar 96 02:02:37 GMT
  6. Approved: fjh@cs.mu.oz.au
  7. Newsgroups: comp.std.c++
  8. Subject: Re: Problem with new in templates...
  9. Organization: Comp Sci, University of Melbourne
  10. References: <adamnash-1303962301470001@gel.stanford.edu>
  11. X-Auth: PGPMoose V1.1 PGP comp.std.c++
  12.     iQBFAgUBMUjPxeEDnX0m9pzZAQGtmQF/bogBIvH/bV09KftATi+3xUYYtSFGIzLJ
  13.     j6695NZ+LXJ5eEUBS1qMvMiXqD2LvnCi
  14.     =7unq
  15.  
  16. adamnash@cs.stanford.edu (Adam Nash) writes:
  17.  
  18. >[...] for semantic reasons, the template assumes that DATA is a pointer type.
  19. [...]
  20. >template <class DATA>
  21. >void GIDTable::ReadFromStream(LStream *inStream)
  22. >{
  23. >   DATA data;
  24. >
  25. >   ...
  26. >
  27. >   data = new DATA;
  28. >   (*data).ReadFromStream(inStream);
  29. >
  30. >   ...
  31. >}
  32. >
  33. >
  34. >The problem occurs on the second line.  data is of type DATA, so you
  35. >really want to allocate a new (*DATA).  IE, if DATA is a CBar *, then data
  36. >is a CBar *,
  37. >so we want it to say: data = new CBar;
  38. >
  39. >How can I do this, only knowing the pointer type?
  40.  
  41. You can use a partial template specialization:
  42.  
  43.     template <class T> struct dereference {};
  44.     template <class T> struct dereference <T*> {
  45.         typedef T type;
  46.     };
  47.         
  48. Then just write
  49.  
  50.     data = new dereference<Data>::type;
  51.  
  52. (I note in passing that this would of course be less obfuscated if C++
  53. supported template typedefs...)
  54.  
  55. Now, the reason that all of this belongs in comp.std.c++ not comp.lang.c++
  56. is that the above code is valid according to the standard, but is highly
  57. unlikely to work with your favourite C++ compiler.  Partial specialization
  58. is a relatively new feature, and few C++ compilers support it yet.
  59.  
  60. --
  61. Fergus Henderson                 WWW: http://www.cs.mu.oz.au/~fjh
  62. fjh@cs.mu.oz.au                  PGP: finger fjh@128.250.37.3
  63. ---
  64. [ comp.std.c++ is moderated.  To submit articles: try just posting with      ]
  65. [ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu         ]
  66. [ FAQ:      http://reality.sgi.com/employees/austern_mti/std-c++/faq.html    ]
  67. [ Policy:   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
  68. [ Comments? mailto:std-c++-request@ncar.ucar.edu                             ]
  69.